<?php

namespace System\Log;

class Logger
{

    /**
     * 日志信息
     * 
     * @access public
     * @var array
     */
    public $messages = [];

    public $flushInterval = 1000;

    public $traceLevel = 0;

    public function init()
    {
        // 注册应用关闭函数
        register_shutdown_function(function ()
        {
            // 注册关闭函数为 ‘flush’
            register_shutdown_function([
                $this,
                'flush',
                TRUE
            ]);
        });
    }

    /**
     * 组装日志信息
     * 
     * @access public
     * @param string $message 日志消息
     * @param int $level 日志级别
     * @param string $category 日志应用
     * @return void 没有返回值
     */
    public function log($message, $level, $category = 'applicaction')
    {
        $time = microtime(TRUE);
        $traces = [];
        if ($this->traceLevel > 0) {
            $count = 0;
            $ts = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
            array_pop($ts);
            foreach ($ts as $trace) {
                if (isset($trace['file'], $trace['line']) && strpos($trace['file'], DREAM_PATH) !== 0) {
                    unset($trace['object'], $trace['args']);
                    $traces[] = $trace;
                    if (++ $count >= $this->tracelevel) {
                        break;
                    }
                }
            }
        }
        $this->messages[] = [
            $message,
            $level,
            $category,
            $time,
            $traces
        ];
        if ($this->flushInterval > 0 && count($this->messages) >= $this->flushInterval) {
            $this->flush();
        }
    }

    public function flush($final = FALSE)
    {
        $messages = $this->messages;
        $this->messages = [];
        if ($this->dispatcher instanceof Dispatcher) {
            $this->dispatcher->dispatch($messages, $final);
        }
    }
}
